package org.zkpk.wordcount;

import java.io.IOException;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
class souMap extends Mapper<LongWritable, Text, Text, IntWritable> {

	public void map(
			LongWritable key,
			Text value,
			org.apache.hadoop.mapreduce.Mapper<LongWritable, Text, Text, IntWritable>.Context context) {
		String ss = value.toString();
		String[] arr = ss.split("\t");

		try {
			context.write(new Text(arr[1]), new IntWritable(1));
		} catch (IOException | InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

class souRedoce extends Reducer<Text, IntWritable, Text, IntWritable> {
	private static int num = 1;
	public void reduce(
			Text key,
			java.lang.Iterable<IntWritable> values,
			org.apache.hadoop.mapreduce.Reducer<Text, IntWritable, Text, IntWritable>.Context context) {
		int sum = 0;
		for(IntWritable count : values){
			sum+=count.get();
		}
		if(sum>20){
			try {
				context.write(new Text(String.valueOf(num) + "\t" + key), new IntWritable(sum));
			} catch (IOException | InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			num++;
		}
	}
}

public class sougouMap {
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		String inPath = args[0];
		String outPath = args[1];
		
		Job job =Job.getInstance();
		job.setJobName("sougouMap");
		job.setJarByClass(sougouMap.class);
		job.setMapperClass(souMap.class);
		job.setReducerClass(souRedoce.class);
		
		job.setInputFormatClass(TextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		FileInputFormat.addInputPath(job, new Path(inPath));
        FileOutputFormat.setOutputPath(job, new Path(outPath));
        
        job.waitForCompletion(true);
	}
}